import checkAccess from "@/access/checkAccess";
import router from "@/router";
import store from "@/store";
import ACCESS_ENUM from "@/access/accessEnum";

router.beforeEach(async (to, from, next) => {
  const loginUser = store.state.user.loginUser;
  if (!loginUser || !loginUser.userRole) {
    await store.dispatch("user/getLoginUser");
  }

  const needAccess =
    (to.meta?.access as string | string[]) ?? ACCESS_ENUM.NOT_LOGIN;
  // 要跳转页面需要登录
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    // 没有登录，跳转登录页
    if (!loginUser || !loginUser.userRole) {
      next("/user/login?redirect=" + to.fullPath);
      return;
    }
    if (!checkAccess(loginUser, needAccess)) {
      next("/noAuth");
      return;
    }
  }

  next();
});
